package com.sky.service.admin.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.admin.DishFlavorMapper;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealDishMapper;
import com.sky.mapper.admin.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.admin.DishService;
import com.sky.vo.DishVO;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

@Slf4j
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 菜单分页模糊查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult selectPage(DishPageQueryDTO dishPageQueryDTO) {
        // 开始分页
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> dishVOPage = dishMapper.selectPage(dishPageQueryDTO);
//
//        // 收集满足条件的数据
//        List<DishVO> filteredList = dishVOPage.getResult().stream()
//                .filter(dishVO -> !StatusConstant.DISABLE.equals(dishVO.getStatus()))
//                .collect(Collectors.toList());
//
//        // 创建新的分页对象
//        Page<DishVO> filteredPage = new Page<>(dishVOPage.getPageNum(), dishVOPage.getPageSize(), dishVOPage.isCount());
//        filteredPage.addAll(filteredList);
//        filteredPage.setTotal(filteredList.size());
//
//        return new PageResult(filteredPage.getTotal(), filteredPage.getResult());
        return new PageResult(dishVOPage.getTotal(), dishVOPage.getResult());
    }


    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Transactional
    @Override       // 可省略
    public void insert(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        dishMapper.insert(dish);
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();

        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            log.info("获取到的口味列表为：{}", flavors );
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {

        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        List<Long> setmealIds = setmealDishMapper.getSetmealIdsBySetmealDishId(ids);
        if (setmealIds != null && !setmealIds.isEmpty()){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        for (Long id : ids){
            dishMapper.deleteById(id);
            dishFlavorMapper.deleteByDishId(id);
        }

    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> selectList(Long categoryId) {
        return dishMapper.selectList(categoryId);
    }

    /**
     * 菜品回显
     *
     * @param id
     * @return
     */
    @Override
    public DishVO selectById(Long id) {

        // 获取dish 对象
        Dish dish = dishMapper.selectById(id);
        log.info("dish根据id获取的内容为{}" ,dish);
        // 获取dish_flavor对象并遍历插入到dishVo中
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        log.info("dishFlavours根据id获取的内容为{}" ,dishFlavors);
        dishVO.setFlavors(dishFlavors);

        return dishVO;

    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Transactional
    @Override
    public void update(DishDTO dishDTO) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        Long id = dishDTO.getId();
        log.warn("删除传入的dish id为{}", id);

        if (CollectionUtils.isEmpty(dishDTO.getFlavors())){
            throw new DeletionNotAllowedException(MessageConstant.NULL_CHOICE);
        }

        // 检查每一个 DishFlavor 对象的 name 属性是否为空
        boolean anyNameIsEmpty = dishDTO.getFlavors().stream()
                .anyMatch(flavor -> flavor.getName() == null || flavor.getName().isEmpty());
        // 如果没有选择口味则抛出异常
        if (anyNameIsEmpty) {
            throw new DeletionNotAllowedException(MessageConstant.NULL_CHOICE);
        }

        // 继续执行删除操作
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
        }
        dishFlavorMapper.insertBatch(flavors);
    }

    /**
     * 菜品起售停售
     *
     * @param status
     * @param id
     */
    @Override
    public void status(Integer status, Long id) {
        // 修改菜品状态
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        if (dish.getStatus() == StatusConstant.ENABLE) {
            // 根据菜品id获取包含菜品的套餐
            List<Long> setmealIds = setmealDishMapper.selectSetmealByDishId(id);
            // todo 逻辑不明确
            // 将查询到的套餐进行停售
            if (setmealIds != null && !setmealIds.isEmpty()) {
                setmealIds.forEach(setmealId -> {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.ENABLE)
                            .build();
                    setmealMapper.status(setmeal);
                });
            }
        }
    }

}


